package com.gitee.huxing.course.conc.conc03.tool;

import java.util.concurrent.Semaphore;

/**
 * @Description:
 * @ProjectName: JavaCourse
 * @Package: com.gitee.huxing.course.conc.conc03.tool
 * @ClassName: SemaphoreDemo1
 * @Author: huxingmale
 * @DateTime: 2021-08-26 0:22
 */
public class SemaphoreDemo1 {

    public static void main(String[] args) {
        int N = 8;  // 工人数
        Semaphore semaphore = new Semaphore(2);   // 机器数目
        for (int i = 0; i < N; i++) {
            new Worker(i, semaphore).start();
        }
    }

    static class Worker extends Thread{
        private int num;
        private Semaphore semaphore;

        public Worker(int num, Semaphore semaphore){
            this.num = num;
            this.semaphore = semaphore;
        }

        @Override
        public void run() {
            try {
                semaphore.acquire(); // 在子线程里面控制资源
                System.out.println("工人" + this.num + "占用一个机器在生产...");
                Thread.sleep(1000L);
                System.out.println("工人" + this.num + "释放出机器");
                semaphore.release();   // 在子线程里控制释放资源占用
            } catch (InterruptedException ex){
                ex.printStackTrace();
            }
        }
    }
}
